<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="machineryTypeName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style="height:100vh;overflow-y:auto;">
          <el-tree
            :data="machineryTypeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :renderContent = "renderTreeNodeContent"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--设备数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="设备编码" prop="machineryCode">
            <el-input
              v-model="queryParams.machineryCode"
              placeholder="请输入设备编码"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="设备名称" prop="machineryName">
            <el-input
              v-model="queryParams.machineryName"
              placeholder="请输入设备名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['mes:device:add']"
              >新增</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['mes:device:edit']"
            >修改2</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['mes:device:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['mes:device:import']"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['mes:device:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="machineryList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" align="center" width="50"/>
          <el-table-column label="设备编码" width="120" align="center" key="machineryCode" prop="machineryCode">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleView(scope.row)"
                >{{ scope.row.machineryCode }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="设备名称" min-width="120" align="left" key="machineryName" prop="machineryName" :show-overflow-tooltip="true"/>
          <el-table-column label="品牌" align="left" key="machineryBrand" prop="machineryBrand" :show-overflow-tooltip="true"/>
          <el-table-column label="规格型号" align="left" key="machinerySpec" prop="machinerySpec" :show-overflow-tooltip="true"/>
          <el-table-column label="设备类型" min-width="120" align="center" key="machineryTypeName" prop="machineryTypeName" :show-overflow-tooltip="true"/>
          <el-table-column label="所属车间" align="center" key="workshopName" prop="workshopName" :show-overflow-tooltip="true"/>
          <el-table-column label="设备状态" align="center" key="status" prop="status">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.mes_machinery_status"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column label="设备数量" align="center" key="attr3" prop="attr3" :show-overflow-tooltip="true"/>
          <el-table-column label="失效日期" align="center" prop="attr1" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.attr1, "{y}-{m}-{d}") }}</span>
            </template> 
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="220"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['mes:device:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['mes:device:remove']"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="openTrack(scope.row)"
                >查看保养情况</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备编码" prop="itemCode">
              <el-input
                v-model="form.machineryCode"
                readonly="readonly"
                maxlength="64"
                v-if="optType == 'view'"
              />
              <el-input
                v-model="form.machineryCode"
                placeholder="请输入设备编码"
                maxlength="64"
                v-else
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)"
                v-if="optType != 'view'"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="itemName">
              <el-input
                v-model="form.machineryName"
                maxlength="255"
                readonly="readonly"
                v-if="optType == 'view'"
              />
              <el-input
                v-model="form.machineryName"
                placeholder="请输入设备名称"
                maxlength="255"
                v-else
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="machineryBrand">
              <el-input
                v-model="form.machineryBrand"
                maxlength="255"
                readonly="readonly"
                v-if="optType == 'view'"
              />
              <el-input
                v-model="form.machineryBrand"
                placeholder="请输入品牌"
                maxlength="255"
                v-else
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备分类" prop="machineryTypeId">
              <treeselect
                v-model="form.machineryTypeId"
                :options="machineryTypeOptions"
                :normalizer="normalizer"
                disabled
                v-if="optType == 'view'"
              />
              <treeselect
                v-model="form.machineryTypeId"
                :options="machineryTypeOptions"
                :normalizer="normalizer"
                placeholder="请选择所属分类"
                v-else
                :disable-branch-nodes="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="machinerySpec">
              <el-input
                v-model="form.machinerySpec"
                type="textarea"
                maxlength="255"
                readonly="readonly"
                v-if="optType == 'view'"
              />
              <el-input
                v-model="form.machinerySpec"
                type="textarea"
                placeholder="请输入规格型号"
                maxlength="255"
                v-else
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
              <el-select v-model="form.workshopId" placeholder="请选择车间">
                <el-option
                  v-for="item in workshopOptions"
                  :key="item.workshopId"
                  :label="item.workshopName"
                  :value="item.workshopId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择设备状态">
                <el-option
                  v-for="item in dict.type.mes_machinery_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" prop="attr1">
              <el-date-picker
                clearable
                v-model="form.attr1"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择失效日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                readonly
                v-if="optType == 'view'"
              ></el-input>
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                v-else
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view'"
          >返回</el-button
        >
        <el-button type="primary" @click="submitForm" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的设备数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="title1"
      :visible.sync="open1"
      width="1200px"
      append-to-body
    >
      <el-table v-loading="loading1" :data="trackList">
        <el-table-column
          label="计划编码"
          align="center"
          prop="planCode"
          width="120px"
        />
        <el-table-column label="计划名称" align="center" prop="planName" />
        <el-table-column
          label="计划类型"
          align="center"
          width="120px"
          prop="planType"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.dv_plan_type"
              :value="scope.row.planType"
            />
          </template>
        </el-table-column>
        <el-table-column label="月份" align="center" prop="month" width="90">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.month, "{y}-{m}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.check_plan_track_status"
              :value="scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="handleName" />
        <el-table-column
          label="处理时间"
          align="center"
          prop="handleTime"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.handleTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="跟踪情况" align="center" prop="explain" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="showFile(scope.row)"
              v-if="scope.row.status == '2'"
              >附件预览</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total1 > 0"
        :total="total1"
        :page.sync="queryParams1.pageNum"
        :limit.sync="queryParams1.pageSize"
        @pagination="showTrack"
      />
    </el-dialog>

    <el-dialog :title="title2" :visible.sync="open2" width="40%" append-to-body>
      <el-table v-loading="false" :data="fileList">
        <el-table-column label="文件名称" align="center" prop="fileName" />
        <el-table-column
          label="附件列"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <!-- add begin by zyj 2024/10/17 增加附件下载功能-->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="downloadFile(scope.row)"
              >下载附件</el-button
            >
            <!-- add end by zyj 2024/10/17 增加附件下载功能-->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="openFile(scope.row)"
              >查看附件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="title2" :visible.sync="open3" width="80%" append-to-body>
      <div slot="footer" class="dialog-footer">
        <vue-office-pdf
          v-if="showFileType == 'pdf'"
          :src="dateUrl"
          style="width: 100%; height: 600px"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
        <div
          v-if="
            showFileType == 'PNG' ||
            showFileType == 'png' ||
            showFileType == 'JPG' ||
            showFileType == 'jpg' ||
            showFileType == 'jpeg' ||
            showFileType == 'JPEG'
          "
        >
          <el-image
            @load="renderedHandler"
            @error="errorHandler"
            :src="dateUrl"
            style="width: 100%; height: 600px"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMachinery,
  getMachinery,
  delMachinery,
  addMachinery,
  updateMachinery,
} from "@/api/mes/dv/machinery";
import { listMachinerytype } from "@/api/mes/dv/machinerytype";
import { listAllWorkshop } from "@/api/mes/md/workshop";
import { genCode } from "@/api/mes/md/rule";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getTrackByMachineryId,
  selectFileManageList,
} from "@/api/mes/dv/track";
import { Message } from "element-ui";
import VueOfficePdf from "@vue-office/pdf";

export default {
  name: "Machinery",
  dicts: ["sys_yes_no", "mes_machinery_status"],
  components: { Treeselect, VueOfficePdf },
  data() {
    
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      loading1: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total1: 0,
      // 物料产品表格数据
      machineryList: [],
      // 弹出层标题
      title: "",
      title1: "设备保养情况",
      title2: "文件预览",
      // 设备类型树选项
      machineryTypeOptions: [],
      // 设备类型树数据
      machineryTypeData: [],
      //车间选项
      workshopOptions: [],
      //车间选项数据
      workshopData: [],
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      open3: false,
      dateUrl: null,
      showFileType: [],
      trackList: [],
      fileList: [],
      // 设备类型名称
      machineryTypeName: undefined,
      //自动生成物料编码标识
      autoGenFlag: false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "machineryTypeName",
        //add begin by zyj 2024-10-17 故障，停用用红色标注
        class: "is-err"
        //add end by zyj 2024-10-17 故障，停用用红色标注

      },
      // 员工导入参数
      upload: {
        // 是否显示弹出层（员工导入）
        open: false,
        // 弹出层标题（员工导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的员工数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/dv/machinery/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machineryCode: null,
        machineryName: null,
        machineryBrand: null,
        machinerySpec: null,
        machineryTypeId: null,
        machineryTypeCode: null,
        machineryTypeName: null,
        workshopId: null,
        workshopCode: null,
        workshopName: null,
        status: null,
      },

      queryParams1: {
        id: null,
        pageNum: 1,
        pageSize: 10,
      },

      // 表单校验
      rules: {
        machineryCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" },
          { max: 64, message: "设备编码长度必须小于64个字符", trigger: "blur" },
        ],
        machineryName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        workshopId: [
          { required: true, message: "车间不能为空", trigger: "blur" },
        ],
        machineryTypeId: [
          { required: true, message: "设备分类不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    // 根据设备分类名称筛选分类树
    machineryTypeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    // add begin by zyj 2024-10-17 故障，停用用红色标注 
    renderTreeNodeContent(h, {node, data, store}){
      if(data.isErr){
        return h(
          'span',
          {
            class: 'is-err el-tree-node__label',
          },
          node.label
          
        )
      }else{
        return h(
          'span',
          {
            class: 'el-tree-node__label',
          },
          node.label
        )
      }
    },
    // add end by zyj 2024-10-17 故障，停用用红色标注 
    /** 查询物料编码列表 */
    getList() {
      this.loading = true;
      listMachinery(this.queryParams).then((response) => {
        this.machineryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getWorkshops() {
      listAllWorkshop().then((response) => {
        this.workshopOptions = response.data;
      });
    },
    /** 转换设备类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.machineryTypeId,
        label: node.machineryTypeName,
        children: node.children,
      };
    },
    /** 查询设备类型下拉树结构 */
    getTreeselect() {
      listMachinerytype().then((response) => {
        this.machineryTypeOptions = [];
        this.machineryTypeData = response.data;
        const data = this.handleTree(
          response.data,
          "machineryTypeId",
          "parentTypeId"
        );
        data.map((item) => {
          this.machineryTypeOptions.push(item);
        });
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.machineryTypeName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.machineryTypeId = data.machineryTypeId;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        machineryId: null,
        machineryCode: null,
        machineryName: null,
        machineryBrand: null,
        machinerySpec: null,
        machineryTypeId: null,
        machineryTypeCode: null,
        machineryTypeName: null,
        workshopId: null,
        workshopCode: null,
        workshopName: null,
        attr1: null,
        status: "STOP",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.machineryTypeId= null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.machineryId);
      this.queryParams.dvMachineryIdList = selection.map(
        (item) => item.machineryId
      );
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.getTreeselect();
      this.getWorkshops();
      const machineryId = row.machineryId || this.ids;
      getMachinery(machineryId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "查看设备信息";
        this.optType = "view";
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      debugger;
      this.reset();
      this.getTreeselect();
      this.getWorkshops();
      if (this.queryParams.machineryTypeId != 0) {
        this.form.machineryTypeId = this.queryParams.machineryTypeId;
      }
      this.optType = "add";
      this.open = true;
      this.title = "新增设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.getWorkshops();
      const machineryId = row.machineryId || this.ids;
      getMachinery(machineryId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          var param = this.form;
          for (var i = 0; i < this.machineryTypeData.length; i++) {
            if (
              param.machineryTypeId == this.machineryTypeData[i].machineryTypeId
            ) {
              param.machineryTypeName =
                this.machineryTypeData[i].machineryTypeName;
              param.machineryTypeCode =
                this.machineryTypeData[i].machineryTypeCode;
            }
          }
          for (var i = 0; i < this.workshopOptions.length; i++) {
            if (param.workshopId == this.workshopOptions[i].workshopId) {
              param.workshopName = this.workshopOptions[i].workshopName;
              param.workshopCode = this.workshopOptions[i].workshopCode;
            }
          }
          if (this.form.machineryId != undefined) {
            updateMachinery(param).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            debugger;
            addMachinery(param).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const machineryIds = row.machineryId || this.ids;
      this.$modal
        .confirm("确认删除数据项？")
        .then(function () {
          return delMachinery(machineryIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/dv/machinery/export",
        {
          ...this.queryParams,
        },
        `md_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "mes/dv/machinery/importTemplate",
        {},
        `md_item_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("MACHINERY_CODE").then((response) => {
          this.form.machineryCode = response;
        });
      } else {
        this.form.machineryCode = null;
      }
    },
    openTrack(row) {
      const machineryId = row.machineryId || this.ids;
      this.queryParams1.id = machineryId;
      this.showTrack();
    },
    showTrack() {
      this.loading1 = true;
      getTrackByMachineryId(this.queryParams1).then((response) => {
        this.trackList = response.rows;
        this.total1 = response.total;
        this.loading1 = false;
        this.open1 = true;
      });
    },
    showFile(row) {
      const param = {
        type: 3,
        relevanceId: row.id,
      };
      selectFileManageList(param).then((response) => {
        this.open2 = true;
        this.fileList = response.data;
      });
    },
    // add begin by zyj 2024-10-17 增加附件下载功能
    downloadFile(row){
      debugger;
      var image = new Image();
      image.src = row.url;

      image.crossOrigin = "anonymous";
      const dataUrlToBlob = (url)=>{
        let arr = url.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bStr = atob(arr[1]),
        n = bStr.length,
        u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bStr.charCodeAt(n);
        }
        return new Blob([u8arr],{type:mime});
      }
      image.onload = ()=>{
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d")
        context.drawImage(image,0,0,image.width,image.height);
        let url = canvas.toDataURL("image/png");

        var blob = dataUrlToBlob(url);
        let obj_url = URL.createObjectURL(blob);
        var downloadLink= document.createElement("a");
        downloadLink.href = obj_url;
        downloadLink.download = row.fileName;
        downloadLink.click();
      }
    },
    // add end by zyj 2024-10-17 增加附件下载功能
    openFile(row) {
      this.open3 = true;
      this.showFileType = row.fileName.substring(
        row.fileName.lastIndexOf(".") + 1
      );
      this.dateUrl = row.url;
    },
    renderedHandler() {
      console.log("渲染完成111111111111111");
      //   downloadLoadingInstance.close();
    },
    errorHandler(e, data) {
      console.log(e, data, "渲染失败222222222222");
      if (this.url !== "") {
        Message.error("渲染失败！");
      }
      //   downloadLoadingInstance.close();
    },
  },
};
</script>
<!--  add begin by zyj 2024-10-17 故障，停用用红色标注 -->
<style>
.is-err{
  background-color: red;
  color:white;
}
</style>
<!--  add end by zyj 2024-10-17 故障，停用用红色标注 -->
